from django.conf import settings
from decimal import Decimal

from shop.models import Product
from cart.forms import AddingProductToCartForm


class Cart(object):

    def __init__(self, request):

        self.session = request.session
        self.cart = self.session.get(settings.CART_SESSION_ID)
        print(f'self.cart - {self.cart}')
        if not self.cart:
            print('Создана новая корзина')
            self.cart = self.session[settings.CART_SESSION_ID] = {}

    def save(self):

        """ Сохраняем изменения сессии """

        self.session.modified = True


    def get_product(self, slug):

        """ Получаем продукт из модели Product """

        product = Product.objects.get(slug=slug)
        product_id = str(product.id)
        return (product, product_id)


    def add_product(self, slug, quantity, update_quantity):

        """ Добавляем продукт в корзину """

        product, product_id = self.get_product(slug)
        
        if product_id not in self.cart:
            self.cart[product_id] = {'quantity': 0, 'price': str(product.price)}

        if update_quantity:
            self.cart[product_id]['quantity'] = quantity
        else:
            self.cart[product_id]['quantity'] += quantity

        self.save()


    def clear(self):

        """ Очищаем корзину """

        del self.session[settings.CART_SESSION_ID]
        self.save()


    def __iter__(self):

        """ Возвращаем продукт из корзины """

        product_ids = self.cart.keys()
        products = Product.objects.filter(id__in=product_ids)
        cart_copy = self.cart.copy()

        for element in products:

            product = cart_copy[str(element.id)]
            product['price'] = Decimal(product['price'])
            product['final_price'] = product['quantity'] * product['price']
            product['product'] = element

            yield product


    def remove_product(self, slug):

        """ Удаляем продукт из корзины """

        _, product_id = self.get_product(slug)
        del self.cart[product_id]
        self.save()


    def add_quantity_update(self):

        """ Добавляем возможность обновить количество товаров """

        for item in self.cart.values():

            quantity = item['quantity']
            item['update_quantity'] = AddingProductToCartForm(
                    initial={'quantity': quantity, 'update_quantity': True})


    def get_number_products(self):

        """ Получам количество продуктов находящиеся в корзине """

        return sum(item['quantity'] for item in self.cart.values())


    def get_total_price(self):

        """ Получаем общую стоимость всех продуктов """

        return sum(Decimal(item['price']) * item['quantity']
                   for item in self.cart.values())
